/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.depsea.jvm.chapter02.java1;

import java.io.FileNotFoundException;

/**
 * @author jaune
 * @since 1.0.0
 */
public class CustomClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        try {
            byte[] classBody = this.getClassFromCusomPath(name);
            if (classBody == null || classBody.length == 0) {
                throw new FileNotFoundException();
            } else {
                return this.defineClass(name, classBody, 0, classBody.length);
            }

        } catch (FileNotFoundException e) {
            throw new ClassNotFoundException(name, e);
        }
    }

    private byte[] getClassFromCusomPath(String name) {
        // 从自定义路径中加载类
        // 如果执行路径的字节码文件进行了加密，则需要在此方法进行解密操作。
        return null;
    }

    public static void main(String[] args) {
        CustomClassLoader classLoader = new CustomClassLoader();

        try {
            Class<?> clazz = Class.forName("One", true, classLoader);
            Object obj = clazz.newInstance();
            System.out.println(obj.getClass().getClassLoader());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
